<?php
/**
 * Created by PhpStorm.
 * User: dingjinlai
 * Date: 2018/4/24
 * Time: 下午4:04
 */

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @property Category_model  category_model
 * @property goods_model goods_model
 * @property  size_model size_model
 * @property  color_model color_model
 */
class Siteweb extends Admin_Controller
{
    public function index()
    {
        
        $model = get_model('siteweb_model');
    
        $_param_option = array(
            'goods_name' => array(
                'col' => 'col-lg-4',
                'type' => 'text',
                'placeholder' => '输入产品名称、货号'
            )
        );
        
        $web_list = $model->j_list([], '*', 0, 1000, 'is_delete,sort_num');

        $_action_link = array(
            array('href' => base_url('siteweb/set'), 'name' => '添加站点')
        );
        
        $data = array(
            'web_list' => $web_list,
            'param_option' => $_param_option,
            'action_link' => $_action_link
        );

        $data['sync_url'] = 'sync_delete_siteweb';
        
        $this->load->view('siteweb_list', $data);
    }

    public function sync_delete_siteweb(){
        $model = get_model('siteweb_model');
        $params = $_POST;
        $id = $params['id'];
        $act = $params['act'];
        if(empty($id)){
            ajaxReturn(4001, '缺少必要参数');
        }
        $info = $model->j_row(array('web_id' => $id));

        if(empty($info)){
            ajaxReturn(4002, '该消息不存在');
        }


        switch($act){
            case 'del':
                $data = array('is_delete' => 1, 'update_time' => time());
                break;
            case 'open':
                $data = array('is_delete' => 0, 'update_time' => time());
                break;
            default:
                ajaxReturn(4002, '数据错误!');
        }

        $res = $model->j_update($data, array('web_id' => $id));

        if($res){
            ajaxReturn(200, '成功');
        }
        ajaxReturn(4002, '失败');
    }

    public function set()
    {
        $this->load->model('siteweb_model');
        $this->load->library('sys_message');
    
        $assoc = $this->uri->uri_to_assoc();
        
        $web_id = intval($assoc['web_id']);
        
        $web_info = $this->siteweb_model->siteweb_info(array('web_id' => $web_id), 1);
        
        if ($_POST) {
            
            $data = array(
                'web_name' => trim($this->input->post('web_name')),
                'title' => trim($this->input->post('title')),
                'ab_name' => trim($this->input->post('ab_name')),
                'type' => intval($this->input->post('type')),
                'view_id' => intval($this->input->post('view_id')),
                'sort_num' => intval($this->input->post('sort_num')),
                'web_access' => trim($this->input->post('web_access'))
            );
    
            !$data['web_name'] && $this->sys_message->wrong('请填写站点名称！');
            !$data['title'] && $this->sys_message->wrong('请填写产品前缀！');
            !$data['ab_name'] && $this->sys_message->wrong('请填写货号前缀！');
            !$data['web_access'] && $this->sys_message->wrong('请填写网站API！');
            $res = $this->db->from('siteweb')->where(['ab_name'=>$data['ab_name']])->get()->row_array();
            if($res && empty($web_id)){
                $this->sys_message->wrong('货号前缀有重复的');
            }
            $cate_arr = $this->input->post('cate');
            if ($cate_arr) {
                foreach ($cate_arr as $cate) {
                    if ($cate) {
                        $data['cate'][] = trim($cate);
                    }
                }
            }
            
            $tags = explode(',', trim($this->input->post('tags')));
            if($tags) {
                foreach ($tags as $k => $tag) {
                    if ($tag) {
                        $tags[$k] = trim($tag);
                    }
                }
                $data['tags'] = implode(',', $tags);
            }

            
            $this->siteweb_model->insert_siteweb($data, $web_id);
    
            $this->sys_message->success('成功!');
            
        }
        
        $data = array(
            'web_info' => $web_info
        );
        
        $this->load->view('siteweb_set', $data);
    }
    
    public function color_list()
    {
        $this->load->model('color_model');
        $this->load->library('pagination');
    
        $assoc = $this->uri->uri_to_assoc();
    
        $_param_option = array(
            'color_name' => array(
                'col' => 'col-lg-4',
                'type' => 'text',
                'placeholder' => '输入颜色名称'
            )
        );
    
        $_param = array(
            'color_name' => $this->input->get('color_name'),
            'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0
        );
    
        $config['base_url'] = base_url('siteweb/') . 'color_list/page/';
        $config['total_rows'] = $this->color_model->count($_param);
        $config['num_links'] = 6;
        $config['per_page'] = $this->color_model->limit_rows;
        $config['use_page_numbers']=true;
        $this->pagination->initialize($config);
        
        $color_list = $this->color_model->color_list($_param);
    
        $_action_link = array(
            array('href' => base_url('siteweb/color_set'), 'name' => '添加颜色')
        );
        
        $data = array(
            'color_list' => $color_list,
            'pages' => $this->pagination->create_links(),
            'param_option' => $_param_option,
            'param' => $_param,
            'action_link' => $_action_link
        );
        
        $this->load->view('siteweb_color_list', $data);
    }
    
    public function color_set()
    {
    
        $this->load->model('color_model');
        $this->load->library('sys_message');
    
        $assoc = $this->uri->uri_to_assoc();

        $this->config->load('website_common');

        $colors_opint = $this->config->item('colors');
    
        $color_id = intval($assoc['id']);

        $color = $this->color_model->color_info(array('color_id' => $color_id));
    
        if ($_POST) {
        
            $data = array(
                'color_en' => trim($this->input->post('color_en')),
                'color_zh' => trim($this->input->post('color_zh')),
                'option_id' => trim($this->input->post('option_id')),
                'is_delete' => $this->input->post('is_delete'),
                'new_color_code' => trim($this->input->post('new_color_code'))
            );
        
            !$data['color_en'] && $this->sys_message->wrong('请填写颜色英文名称！');
            !$data['color_zh'] && $this->sys_message->wrong('请填写颜色中文名称！');

            $this->color_model->insert_color($data, $color_id);
        
            $this->sys_message->success('成功!');
        }
    
        $data = array(
            'color' => $color,
            'colors_opint' => $colors_opint,
            'color_code' => $this->color_model->code_setting
        );

        $this->load->view('siteweb_color_set', $data);
    }
    
    public function size_list()
    {
        $this->load->model('size_model');
        $this->load->library('pagination');
    
        $assoc = $this->uri->uri_to_assoc();
    
        $_param_option = array(
            'size_name' => array(
                'col' => 'col-lg-4',
                'type' => 'text',
                'placeholder' => '输入尺码名称'
            )
        );
    
        $_param = array(
            'size_name' => $this->input->get('size_name'),
            'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0
        );
    
        $config['base_url'] = base_url('siteweb/') . 'size_list/page/';
        $config['total_rows'] = $this->size_model->count($_param);
        $config['num_links'] = 6;
        $config['per_page'] = $this->size_model->limit_rows;
        $config['use_page_numbers']=true;
        $this->pagination->initialize($config);
    
        $size_list = $this->size_model->size_list($_param);
    
        $_action_link = array(
            array('href' => base_url('siteweb/size_set'), 'name' => '添加尺码')
        );
    
        $data = array(
            'size_list' => $size_list,
            'pages' => $this->pagination->create_links(),
            'param_option' => $_param_option,
            'param' => $_param,
            'action_link' => $_action_link
        );
    
        $this->load->view('siteweb_size_list', $data);
    }
    
    public function size_set()
    {
        $this->load->model('size_model');
        $this->load->library('sys_message');
        
        $assoc = $this->uri->uri_to_assoc();
        
        $size_id = intval($assoc['id']);
        
        $size = $this->size_model->size_info(array('size_id' => $size_id));
        
        if ($_POST) {
            
            $data = array(
                'size_value' => trim($this->input->post('size_value')),
                'size_code' => trim($this->input->post('size_code')),
                'size_type' => intval($this->input->post('size_type')),
                'is_delete' => $this->input->post('is_delete'),
                'new_size_code' => intval($this->input->post('new_size_code'))
            );

            !$data['size_value'] && $this->sys_message->wrong('请填写尺码英文名称！');
            !$data['size_code'] && $this->sys_message->wrong('请填写尺码中文名称！');
            
            $this->size_model->insert_size($data, $size_id);
    
            $this->sys_message->success('成功!');
        }
        
        $data = array(
            'size' => $size,
            'size_code' => $this->size_model->code_setting
        );

        $this->load->view('siteweb_size_set', $data);
    }
    //标签展示
    public function tags_list(){
        $this->load->model('tagslist_model');
        $this->load->library('pagination');
        $assoc = $this->uri->uri_to_assoc();
        $_param_option = array(
            'tags_name' => array(
                'col' => 'col-lg-4',
                'type' => 'text',
                'placeholder' => '输入标签名称'
            )
        );
        $_action_link = array(
            array('href' => base_url('siteweb/tags_add'), 'name' => '添加标签')
        );
        $_param = array(
            'tags_name' => $this->input->get('tags_name'),
            'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0
        );
    
        $config['base_url'] = base_url('siteweb/') . 'tags_list/page/';
        $config['total_rows'] = $this->tagslist_model->count($_param);
        $config['num_links'] = 6;
        $config['per_page'] = $this->tagslist_model->limit_rows;
        $config['use_page_numbers']=true;
        $this->pagination->initialize($config);
    
        $tags_list = $this->tagslist_model->tags_list($_param);
    
        $data = array(
            'tags_list' => $tags_list,
            'pages' => $this->pagination->create_links(),
            'param_option' => $_param_option,
            'param' => $_param,
            'action_link' => $_action_link
        );
        $this->load->view('tags_list',$data);
    }
    //修改状态
    public function tags_show(){
        $this->load->library('sys_message');
        $this->load->model('tagslist_model');
        $id = $this->input->post('id');
        $this->tagslist_model->tags_up_show($id);
        $this->sys_message->success('成功!');
    }

    public function tags_add(){
        if($_POST){
            
            $this->load->model('tagslist_model');
            $tags_name = $this->input->post('tags_name');
            $this->tagslist_model->tags_add($tags_name);
            redirect('Siteweb/tags_list');
        }
        $this->load->view('tags_add');
    }

    /**
     * 分类列表
     * author: walker
     * Date: 2019/11/6
     * Time: 18:13
     * Note:
     */
    public function cat_list(){
        $assoc = $this->uri->uri_to_assoc();
        $this->load->model('category_model');
        $this->load->library('pagination');
        $_param_option = array(
            'cate_name' => array(
                'col' => 'col-lg-4',
                'type' => 'text',
                'placeholder' => '输入分类名称'
            )
        );
        $_action_link = array(
            array('href' => base_url('siteweb/cat_add'), 'name' => '添加分类')
        );
        $_param = array(
            'cate_name' => $this->input->get('cate_name'),
            'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0
        );
    
        $config['base_url'] = base_url('siteweb/') . 'cat_list/page/';
        $config['total_rows'] = $this->category_model->cate_count($_param);
        $config['num_links'] = 6;
        $config['per_page'] = $this->category_model->limit_rows;
        $config['use_page_numbers']=true;
        $this->pagination->initialize($config);

        $this->category_model->limit_rows = 1000;
        $cate_list = $this->category_model->cate_list($_param);

        $this->load->model('goods_model');

        $format_list = array();
        foreach($cate_list as $value){
            if($value['pid'] == 0){
                $value['pid'] = -1;
            }

            $child_data = $this->category_model->j_list(array('pid' => $value['cate_id']), 'cate_id');
            $cat_ids = array_merge(array($value['cate_id']), array_map('current', $child_data));
            $count = $this->goods_model->j_count(array('cat_id' => $cat_ids));

            $format_list[] = array(
                'cate_id' => $value['cate_id'],
                'pid' => $value['pid'],
                'count_num' => $count,
                'cate_name' => $value['cate_name'],
                'is_show' => $value['is_show'] ? '隐藏' : '显示',
            );

        }

        $data = array(
            'cate_list' => $cate_list,
            'format_list' => $format_list,
            'pages' => $this->pagination->create_links(),
            'param_option' => $_param_option,
            'param' => $_param,
            'action_link' => $_action_link
        );

        $this->load->view('cat_list',$data);
    }

    //修改分类状态
    public function cate_show(){
        $this->load->library('sys_message');
        $this->load->model('category_model');
        $cate_id = $this->input->post('cate_id');
        $this->category_model->cate_up_show($cate_id);
        $this->sys_message->success('成功!');
    }

    public function cat_add(){
        $this->load->model('category_model');
        if($_POST){
            $this->load->library('sys_message');
            $param = array(
                    'cate_name' => $this->input->post('cate_name'),
                    'pid' => $this->input->post('pid')
                );
            if($this->input->post('hidden_id')){
                $hidden_id = $this->input->post('hidden_id');
                $this->category_model->cate_update($param,$hidden_id);
                redirect('Siteweb/cat_list');
            }else{
                $this->category_model->cate_add($param);
                redirect('Siteweb/cat_list');
            }
        }else{
            $cate_id = $this->input->get('cate_id');
            if($cate_id){
                $cate = $this->category_model->cate_find($cate_id);
                $category = $this->category_model->cat_one();
                $data = array(
                    'category' => $category,
                    'cate' => $cate,
                );
            }else{
                $category = $this->category_model->cat_one();
                $data = array(
                    'category' => $category,
                );
            }  
        }
        
        
        $this->load->view('cat_add',$data);
    }
    
    public function fabric_list(){
        $_action_link = array(
            array('href' => base_url('siteweb/fabric_add'), 'name' => '添加面料')
        );
        $fabric = $this->db->from('fabric')->get()->result_array();
        $_param_option = array(
            'cate_name' => array(
                // 'col' => 'col-lg-4',
                // 'type' => 'text',
                // 'placeholder' => '输入分类名称'
            )
        );
        $data = array(
            'fabric' => $fabric,
            'param_option' => $_param_option,
            'action_link' => $_action_link
        );
        $this->load->view('fabric_list',$data);
    }

    public function fabric_add(){
        if($_POST){
            $param = array(
                'fabric_name' => $this->input->post('fabric_name'),
                'pid' => $this->input->post('pid'),
            );
            $this->db->insert('fabric',$param);
            redirect('Siteweb/fabric_list');
        }else{
            $fabric = $this->db->from('fabric')->where(['pid'=>0])->get()->result_array();
            $data = array(
                    'fabric' => $fabric,
                );
            $this->load->view('fabric_add',$data);
        }
    }

    public function fabric_delete(){
        $id = $this->input->post('id');
        $is_delete = $this->input->post('is_delete');
        if($is_delete == 0){
            $res = 1;
        }else{
            $res = 0;
        }
        
        $this->db->where(['id'=>$id]);
        $this->db->update('fabric',['is_delete'=>$res]);
    }

    public function shopify_cat_list(){

        $_param_option = array(
            'title' => array(
            )
        );
        $shopify_cat = $this->db->from('shopify_cat')->get()->result_array();
    
        $_action_link = array(
            array('href' => base_url('siteweb/shopify_cat_add'), 'name' => '添加')
        );
        $this->load->model('siteweb_model');
        $siteweb = $this->siteweb_model->siteweb_option(0,array('type' => 1));
        $data = array(
            'shopify_cat' => $shopify_cat,
            'param_option' => $_param_option,
            'action_link' => $_action_link,
            'siteweb_json' => json_encode($siteweb),
        );
        $this->load->view('shopify_cat_list',$data);
    }

    public function shopify_cat_add(){
        $this->load->library('sys_message');
        if ($_POST) {
            $data = array(
                'title' => trim($this->input->post('title')),
                'disjunctive' => $this->input->post('disjunctive'),
                'column' => $this->input->post('column'),
                'relation' => $this->input->post('relation'),
                'condition' => $this->input->post('condition'),
            );
            $val = [];
            foreach ($data['column'] as $k => $v) {
                $val[$k]['column'] = $v;
                $val[$k]['relation'] = $data['relation'][$k];
                $val[$k]['condition'] = $data['condition'][$k];
            }
            unset($data['column']);
            unset($data['relation']);
            unset($data['condition']);
            $data['text'] = json_encode($val);
            $this->db->insert('shopify_cat',$data);
            $this->sys_message->success('成功!');
        }
        $this->load->view('shopify_cat_add',$data);
    }

    public function shopify_cat_del(){
        $this->load->library('sys_message');
        $assoc = $this->uri->uri_to_assoc();
        $id = intval($assoc['id']);
        $this->db->delete('shopify_cat',['id'=>$id]);
        $this->sys_message->success('成功!');
    }

    public function up_shopify_goods_cat(){
        $this->load->library('sys_message');
        $web_id = $this->input->post('web_id');
        $siteweb = $this->db->from('siteweb')->where(['web_id'=>$web_id])->get()->row_array();
        $this->load->library('shopify_api', $siteweb);
        $shopify_cat = $this->db->from('shopify_cat')->get()->result_array();
        foreach ($shopify_cat as $key => $val) {
            if($val['disjunctive'] == 2){
                $disjunctive = true;
            }else{
                $disjunctive = false;
            }
            $data = array('smart_collection'=>
                        array(
                            'title'=>$val['title'],
                            'disjunctive'=>$disjunctive,
                        ),
                    );
            $rules = [];
            foreach (json_decode($val['text'],true) as $k => $v) {
                $rules[] = array(
                    'column'=>$v['column'],
                    'relation'=>$v['relation'],
                    'condition'=>$v['condition'],
                );
            }
            $data['smart_collection']['rules'] = $rules;
            $this->shopify_api->up_shopify_goods_cat($data);
        }
        $this->sys_message->success('成功!');
    }

    public function shopify_cat_save(){
        $assoc = $this->uri->uri_to_assoc();
        if($_POST){
            $this->load->library('sys_message');
            $id = intval($assoc['id']);
            $data = array(
                'title' => trim($this->input->post('title')),
                'disjunctive' => $this->input->post('disjunctive'),
                'column' => $this->input->post('column'),
                'relation' => $this->input->post('relation'),
                'condition' => $this->input->post('condition'),
            );
            $val = [];
            foreach ($data['column'] as $k => $v) {
                $val[$k]['column'] = $v;
                $val[$k]['relation'] = $data['relation'][$k];
                $val[$k]['condition'] = $data['condition'][$k];
            }
            unset($data['column']);
            unset($data['relation']);
            unset($data['condition']);
            $data['text'] = json_encode($val);
            $this->db->where(['id'=>$id]);
            $this->db->update('shopify_cat',$data);
            $this->sys_message->success('成功!');
        }else{
            $id = intval($assoc['id']);
            $res = $this->db->from('shopify_cat')->where(['id'=>$id])->get()->row_array();
            $data = array(
                'res' => $res,
            );
            $this->load->view('shopify_cat_save',$data);
        }
    }

    public function siteweb_copy(){
        if($_POST){
            $this->load->library('sys_message');
            $web_a = $this->input->post('web_a');
            $web_b = $this->input->post('web_b');
            $web_page = $this->input->post('web_page');
            $this->load->library('session');
            $admin_id = $this->session->userdata('admin_id');
            $res = $this->db->from('shopify_copy_page')->where(['uid'=>$admin_id,'a_sitweb_id'=>$web_a,'b_sitweb_id'=>$web_b])->get()->row_array();
            $siteweb = $this->db->from('siteweb')->where(['web_id'=>$web_b])->get()->row_array();
            $this->load->library('shopify_api', $siteweb);
            $shopify_page = $this->shopify_api->shopify_page();
            $page_count = ceil($shopify_page['count'] / 50);
            if(empty($res)){
                $res['page_count'] = $page_count;
                $res['click_page'] = 0;
                $res['uid'] = $admin_id;
                $res['a_sitweb_id'] = $web_a;
                $res['b_sitweb_id'] = $web_b;
                $res['shopify_page'] = 0;
                $this->db->insert('shopify_copy_page',$res);
            }
            if($res['click_page'] + 1 > $res['page_count']){
                $this->db->delete('shopify_copy_page',['id'=>$res['id']]);
                $this->sys_message->wrong('没有数据啦!');
            }
                
            
            
            $goods_list = $this->shopify_api->shopify_goods_list($res['shopify_page']);
           
            foreach($goods_list['products'] as $k => $v){
                $sku = $v['variants'][0]['sku'];
                if(strlen($sku) == 14){
                    $goods_id = $this->db->from('goods')->where(['goods_sn'=>substr(substr($sku,2),0,6)])->select('goods_id')->get()->row_array();
                    $presence = $this->db->from('shopify_goods')->where(['goods_id'=>$goods_id['goods_id'],'web_id'=>$res['b_sitweb_id']])->get()->row_array();
                    if($presence){
                        continue;
                    }
                    $shopify_goods = $this->db->from('shopify_goods')->where(['goods_id'=>$goods_id['goods_id'],'web_id'=>$res['a_sitweb_id']])->get()->row_array();
                    $shopify_goods['web_id'] = $res['b_sitweb_id'];
                    $shopify_goods['shopify_id'] = $v['id'];
                    unset($shopify_goods['sg_id']);
                    $this->db->insert('shopify_goods',$shopify_goods);
                }
            }
            $this->db->where(['uid'=>$admin_id]);
            $this->db->update('shopify_copy_page',['shopify_page'=>$goods_list['page'],'click_page'=>$res['click_page'] + 1]);
           
            $this->sys_message->success('成功!');

        }
        $siteweb = $this->db->from('siteweb')->where(['is_delete'=>0])->get()->result_array();
        $data = array(
            'siteweb' => $siteweb,
        );
        $this->load->view('shopify_copy',$data);
    }
    public function shopify_page(){
        $web_a = $this->input->post('web_a');
        $siteweb = $this->db->from('siteweb')->where(['web_id'=>$web_a])->get()->row_array();
        $this->load->library('shopify_api', $siteweb);
        $shopify_page = $this->shopify_api->shopify_page();
        $page = ceil($shopify_page['count'] / 50);
        echo $page;
    }

    public function goods_type(){
        $_param_option = array(
            'goods_name' => array(
                
            )
        );
        $_action_link = array(
            array('href' => base_url('siteweb/goods_type_add'), 'name' => '添加站点')
        );
        $goods_typestyle = $this->db->from('goods_typestyle')->where(['pid'=>0])->get()->result_array();
        foreach ($goods_typestyle as $key => $value) {
            $goods_type = $this->db->from('goods_typestyle')->where(['pid'=>$value['id']])->get()->result_array();
            $goods_typestyle[$key]['val'] = $goods_type;
        }
        $data = array(
            'param_option' => $_param_option,
            'goods_typestyle' => $goods_typestyle,
            'action_link' => $_action_link
        );
        $data['sync_url'] = 'goods_type_del';
        $this->load->view('goods_type',$data);
    }

    public function goods_type_add(){
        $goods_typestyle = $this->db->from('goods_typestyle')->where(['pid'=>0])->get()->result_array();
        $data = array(
            'goods_typestyle' => $goods_typestyle,
        );
        if($_POST){
            $this->load->library('sys_message');
            $arr = array(
                'type_name' => trim($this->input->post('type_name')),
                'pid' => trim($this->input->post('pid'))
            );
            $this->db->insert('goods_typestyle',$arr);
            $this->sys_message->success('成功!');
        }
        $this->load->view('goods_type_add',$data);
    }

    public function goods_type_del(){
        $params = $_POST;
        if($params['act'] == 'del'){
            $is_del = 1;
        }else{
            $is_del = 0;
        }
        $this->db->where(['id'=>$params['id']]);
        $this->db->update('goods_typestyle',['is_del'=>$is_del]);
        ajaxReturn(200, '成功');
    }
}
